package component

import (
	"fmt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
	"path/filepath"
	"time"
)

var Log *zap.SugaredLogger

func initLog() {
	subPath := ConfigObj.GetString("log.log_path")
	defaultLog := ConfigObj.GetString("log.default_log")

	logger := NewLog(subPath, defaultLog)
	Log = logger.Sugar()
	fmt.Println("-->加载log完成")
}

func NewLog(subPath string, fileName string) *zap.Logger {
	runMode := ConfigObj.GetString("mode")
	logRoot := rootPath + ConfigObj.GetString("log.log_root")
	logDir := filepath.Join(logRoot, subPath)
	_, err := os.Stat(logDir)
	if err != nil {
		if os.IsNotExist(err) {
			err := os.MkdirAll(logDir, os.ModePerm)
			if err != nil {
				panic(fmt.Errorf("mkdir failed![%w]\n", err))
			}
		}
	}

	// 设置一些基本日志格式 具体含义还比较好理解，直接看zap源码也不难懂
	//encoder := zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
	encodeConfig := zapcore.EncoderConfig{
		MessageKey:    "msg",
		LevelKey:      "level",
		TimeKey:       "ts",
		CallerKey:     "caller",
		StacktraceKey: "trace",
		LineEnding:    zapcore.DefaultLineEnding,
		EncodeLevel:   zapcore.LowercaseLevelEncoder,
		//EncodeLevel:    zapcore.CapitalLevelEncoder,
		//EncodeCaller: zapcore.ShortCallerEncoder,
		EncodeCaller: zapcore.FullCallerEncoder,
		EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString(t.Format("2006-01-02 15:04:05"))
		},
		//EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeDuration: func(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendInt64(int64(d) / 1000000)
		},
	}
	jsonEncoder := zapcore.NewJSONEncoder(encodeConfig)

	// 实现两个判断日志等级的interface
	infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl == zapcore.InfoLevel
	})

	warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.WarnLevel
	})

	// 获取 info、warn日志文件的io.Writer 抽象 getWriter() 在下方实现
	infoFile := getWriter(fileName+".log", logDir)
	errorFile := getWriter(fileName+"-err.log", logDir)

	coreTee := []zapcore.Core{
		zapcore.NewCore(jsonEncoder, zapcore.AddSync(infoFile), infoLevel),
		zapcore.NewCore(jsonEncoder, zapcore.AddSync(errorFile), warnLevel),
	}

	//dev 模式添加debug日志
	if runMode == "dev" {
		debugFile := getWriter(fileName+"-debug.log", logDir)
		debugLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
			return lvl == zapcore.DebugLevel && runMode == "dev"
		})
		coreTee = append(coreTee, zapcore.NewCore(jsonEncoder, zapcore.AddSync(debugFile), debugLevel))
	}

	if ConfigObj.GetBool("log.console_output") == true {
		consoleEncoder := zapcore.NewConsoleEncoder(encodeConfig)
		infoConsole := os.Stdout
		errorConsole := os.Stdout
		coreTee = append(
			coreTee,
			zapcore.NewCore(consoleEncoder, zapcore.AddSync(infoConsole), infoLevel),
			zapcore.NewCore(consoleEncoder, zapcore.AddSync(errorConsole), warnLevel),
		)
	}

	// 最后创建具体的Logger
	core := zapcore.NewTee(coreTee...)

	// 需要传入 zap.AddCaller() 才会显示打日志点的文件名和行数, 有点小坑
	//logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zap.ErrorLevel))
	logger := zap.New(core, zap.AddStacktrace(zap.ErrorLevel))

	defer logger.Sync()
	return logger
}

func getWriter(filename string, logDir string) io.Writer {
	// 生成rotatelogs的Logger 实际生成的文件名 demo.log.YYmmddHH
	// demo.log是指向最新日志的链接
	// 保存7天内的日志，每1小时(整点)分割一次日志
	hook, err := rotatelogs.New(
		logDir+string(filepath.Separator)+"%Y-%m-%d-"+filename,
		//rotatelogs.WithLinkName(filename),
		rotatelogs.WithMaxAge(time.Hour*24*7),
		rotatelogs.WithRotationTime(time.Hour*24),
	)
	if err != nil {
		panic(err)
	}
	return hook
}
